package com.sangmo.fts.process.storage.service;

import com.sangmo.boot.framework.plugin.dataview.crud.service.BaseViewService;
import com.sangmo.boot.framework.plugin.dataview.data.IDataViewRepo;
import com.sangmo.fts.common.authority.service.AuthorityEntityService;
import com.sangmo.fts.common.utils.RandomUtils;
import com.sangmo.fts.process.storage.interfaces.CsfDraftCreation;
import com.sangmo.fts.process.storage.model.CsfContract;
import com.sangmo.fts.process.storage.model.CsfDraft;
import com.sangmo.fts.process.storage.model.CsfLoan;
import com.sangmo.fts.process.storage.repo.CsfDraftRepo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;

@Service
@Transactional
public class CsfDraftEntityService extends AuthorityEntityService<CsfDraft> {

    @Autowired
    private CsfDraftRepo csfDraftRepo;

    @Autowired
    private CsfLoanService csfLoanService;

    @Autowired
    private CsfContractService csfContractService;

    @Override
    protected IDataViewRepo<CsfDraft> getRepo() {
        return csfDraftRepo;
    }

    @Override
    protected void onCreate(CsfDraft entity, Object bo) {
        super.onCreate(entity, bo);
        entity.setCode(RandomUtils.generateRandomNum(8));
        CsfDraftCreation creation = (CsfDraftCreation) bo;
        CsfLoan loan = csfLoanService.get(creation.getLoanId());
        CsfContract contract = csfContractService.get(loan.getContractId());
        entity.setDrawerId(contract.getBuyerId());
        entity.setPayeeId(contract.getSellerId());
        entity.setAmount(loan.getAmount());
        entity.setBankId(loan.getBankId());
        entity.setFee(loan.getAmount().multiply(new BigDecimal("0.005")));
    }
}
